import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';

class AlertDialogRoute extends StatefulWidget {
  const AlertDialogRoute({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _AlertDialogRouteState();
}

class _AlertDialogRouteState extends State<AlertDialogRoute> {
  final logger = Logger(printer: LogfmtPrinter());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('对话框详解'),
      ),
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              ElevatedButton(
                onPressed: () async {
                  var r = await showDialog<bool>(
                      context: context,
                      builder: (context) {
                        return AlertDialog(
                          title: const Text("提示"),
                          content: const Text("您确定要删除当前文件吗?"),
                          actions: <Widget>[
                            TextButton(
                              child: const Text("取消",
                                  style: TextStyle(color: Colors.grey)),
                              onPressed: () =>
                                  Navigator.of(context).pop(false), //关闭对话框
                            ),
                            TextButton(
                              child: const Text("删除"),
                              onPressed: () {
                                // ... 执行删除操作
                                Navigator.of(context).pop(true); //关闭对话框
                              },
                            ),
                          ],
                        );
                      });
                  logger.i("showDialog:  $r");
                },
                child: const Text("Alert Dialog"),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  var r = await showDialog<int>(
                      context: context,
                      builder: (context) {
                        return SimpleDialog(
                          title: const Text('请选择语言'),
                          children: <Widget>[
                            SimpleDialogOption(
                              child: const Padding(
                                padding: EdgeInsets.symmetric(vertical: 6),
                                child: Text('中文简体'),
                              ),
                              onPressed: () => Navigator.pop(context, 1),
                            ),
                            SimpleDialogOption(
                              child: const Padding(
                                padding: EdgeInsets.symmetric(vertical: 6),
                                child: Text('USA English'),
                              ),
                              onPressed: () => Navigator.pop(context, 2),
                            ),
                          ],
                        );
                      });
                  logger.i("SimpleDialog:  $r");
                },
                child: const Text("Simple Dialog"),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  var r = await showDialog<int>(
                    context: context,
                    builder: (context) {
                      var child = Column(
                        children: <Widget>[
                          const ListTile(title: Text("请选择")),
                          Expanded(
                            child: ListView.builder(
                              itemCount: 30,
                              itemBuilder: (context, index) {
                                return ListTile(
                                  title: Text('$index'),
                                  onTap: () => Navigator.pop(context, index),
                                );
                              },
                            ),
                          ),
                          ListTile(
                            subtitle: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: <Widget>[
                                TextButton(
                                  child: const Text("取消",
                                      style: TextStyle(color: Colors.grey)),
                                  onPressed: () =>
                                      Navigator.of(context).pop(0), //关闭对话框
                                ),
                                TextButton(
                                  child: const Text("删除"),
                                  onPressed: () => Navigator.of(context).pop(0),
                                ),
                              ],
                            ),
                          ),
                        ],
                      );
                      return Dialog(
                        child: SizedBox(
                          height: 400,
                          child: child,
                        ),
                      );
                    },
                  );
                  logger.i("Dialog:  $r");
                },
                child: const Text("Dialog"),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  var r = await showCustomDialog<bool>(
                    context: context,
                    builder: (context) {
                      return AlertDialog(
                        title: const Text("提示"),
                        content: const Text("您确定要删除当前文件吗?"),
                        actions: <Widget>[
                          TextButton(
                            child: const Text("取消"),
                            onPressed: () => Navigator.of(context).pop(false),
                          ),
                          TextButton(
                            child: const Text("删除"),
                            onPressed: () => Navigator.of(context).pop(true),
                          ),
                        ],
                      );
                    },
                  );
                  logger.i("Custom Dialog:  $r");
                },
                child: const Text("Custom Dialog"),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  var _withTree = false;
                  var r = await showCustomDialog<bool>(
                    context: context,
                    builder: (context) {
                      return AlertDialog(
                        title: const Text("提示"),
                        content: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            const Text("您确定要删除当前文件吗?"),
                            Row(
                              children: <Widget>[
                                const Text("同时删除子目录？"),
                                DialogCheckbox(
                                  value: _withTree,
                                  onChanged: (newValue) =>
                                      _withTree = newValue!,
                                ),
                              ],
                            ),
                          ],
                        ),
                        actions: <Widget>[
                          TextButton(
                            child: const Text("取消"),
                            onPressed: () => Navigator.of(context).pop(false),
                          ),
                          TextButton(
                            child: const Text("删除"),
                            onPressed: () => Navigator.of(context).pop(true),
                          ),
                        ],
                      );
                    },
                  );
                  logger.i("Dialog Checkbox:  $r  $_withTree");
                },
                child: const Text("Dialog Checkbox"),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  var _withTree = false;
                  var r = await showCustomDialog<bool>(
                    context: context,
                    builder: (context) {
                      return AlertDialog(
                        title: const Text("提示"),
                        content: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            const Text("您确定要删除当前文件吗?"),
                            Row(
                              children: <Widget>[
                                const Text("同时删除子目录？"),
                                Builder(builder: (context) {
                                  return Checkbox(
                                    value: _withTree,
                                    onChanged: (newValue) {
                                      (context as Element).markNeedsBuild();
                                      _withTree = newValue!;
                                    },
                                  );
                                }),
                              ],
                            ),
                          ],
                        ),
                        actions: <Widget>[
                          TextButton(
                            child: const Text("取消"),
                            onPressed: () => Navigator.of(context).pop(false),
                          ),
                          TextButton(
                            child: const Text("删除"),
                            onPressed: () => Navigator.of(context).pop(true),
                          ),
                        ],
                      );
                    },
                  );
                  logger.i("Dialog Checkbox2:  $r  $_withTree");
                },
                child: const Text("Dialog Checkbox 2"),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  var r = await showModalBottomSheet<int?>(
                    context: context,
                    builder: (context) {
                      return ListView.builder(
                        itemCount: 30,
                        itemBuilder: (context, index) {
                          return ListTile(
                            title: Text("$index"),
                            onTap: () => Navigator.of(context).pop(index),
                          );
                        },
                      );
                    },
                  );
                  logger.i("显示底部菜单列表:  $r");
                },
                child: const Text("显示底部菜单列表"),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  var r = await showDialog(
                    context: context,
                    barrierDismissible: true, //点击遮罩不关闭对话框
                    builder: (context) {
                      return AlertDialog(
                        content: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: const <Widget>[
                            CircularProgressIndicator(),
                            Padding(
                              padding: EdgeInsets.only(top: 26.0),
                              child: Text("正在加载，请稍后..."),
                            ),
                          ],
                        ),
                      );
                    },
                  );
                  logger.i("Loading...:  $r");
                },
                child: const Text("Loading..."),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  var r = await showDialog(
                    context: context,
                    barrierDismissible: true, //点击遮罩不关闭对话框
                    builder: (context) {
                      return UnconstrainedBox(
                        child: SizedBox(
                          width: 280,
                          child: AlertDialog(
                            content: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: const <Widget>[
                                CircularProgressIndicator(),
                                Padding(
                                  padding: EdgeInsets.only(top: 26.0),
                                  child: Text("正在加载，请稍后..."),
                                ),
                              ],
                            ),
                          ),
                        ),
                      );
                    },
                  );
                  logger.i("SizedBox Loading ...:  $r");
                },
                child: const Text("SizedBox Loading..."),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  var date = DateTime.now();
                  var r = await showDatePicker(
                    context: context,
                    initialDate: date,
                    firstDate: date,
                    lastDate: date.add(const Duration(days: 30)),
                  );
                  logger.i("DatePicker ...:  $r");
                },
                child: const Text("DatePicker"),
              ),
              const SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  var date = DateTime.now();
                  var r = await showCupertinoModalPopup(
                    context: context,
                    builder: (ctx) {
                      return SizedBox(
                        height: 200,
                        child: CupertinoDatePicker(
                          mode: CupertinoDatePickerMode.dateAndTime,
                          minimumDate: date,
                          maximumDate: date.add(const Duration(days: 30)),
                          onDateTimeChanged: (DateTime value) {
                            Navigator.of(ctx).pop(value);
                          },
                        ),
                      );
                    },
                  );
                  logger.i("Cupertino DatePicker ...:  $r");
                },
                child: const Text("Cupertino DatePicker"),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<T?> showCustomDialog<T>(
      {required BuildContext context,
      bool barrierDismissible = true,
      required WidgetBuilder builder,
      ThemeData? theme}) {
    return showGeneralDialog(
      context: context,
      pageBuilder: (BuildContext context, Animation<double> animation,
          Animation<double> secondaryAnimation) {
        var pageChild = Builder(builder: builder);
        return SafeArea(
          child: Builder(
            builder: (BuildContext context) {
              if (theme != null) {
                return Theme(data: theme, child: pageChild);
              } else {
                return pageChild;
              }
            },
          ),
        );
      },
      barrierDismissible: barrierDismissible,
      barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
      barrierColor: Colors.black87,
      // 自定义遮罩颜色
      transitionDuration: const Duration(milliseconds: 150),
      transitionBuilder: _buildMaterialDialogTransitions,
    );
  }

  Widget _buildMaterialDialogTransitions(
      BuildContext context,
      Animation<double> animation,
      Animation<double> secondaryAnimation,
      Widget child) {
    return ScaleTransition(
      scale: CurvedAnimation(
        parent: animation,
        curve: Curves.easeOut,
      ),
      child: child,
    );
  }
}

class DialogCheckbox extends StatefulWidget {
  const DialogCheckbox({Key? key, required this.onChanged, this.value})
      : super(key: key);

  final ValueChanged<bool?> onChanged;

  final bool? value;

  @override
  State<StatefulWidget> createState() => _DialogCheckboxState();
}

class _DialogCheckboxState extends State<DialogCheckbox> {
  bool? value;

  @override
  void initState() {
    value = widget.value;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Checkbox(
      value: value,
      onChanged: (newVal) {
        setState(() {
          widget.onChanged(newVal);
          value = newVal;
        });
      },
    );
  }
}
